package com.ynu.springbootappdemo.controller;


import com.ynu.springbootappdemo.common.utils.BaseResponse;
import com.ynu.springbootappdemo.common.utils.ResultUtils;
import com.ynu.springbootappdemo.model.dto.address.UpdateAddressDTO;
import com.ynu.springbootappdemo.model.entity.DeliveryAddress;
import com.ynu.springbootappdemo.model.vo.DeliveryAddressVo;
import com.ynu.springbootappdemo.service.DeliveryAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "地址")
@RestController
@RequestMapping("/address")
public class DeliveryController {
    @Resource
    private DeliveryAddressService service;

    @Resource
    private ModelMapper modelMapper;

    @GetMapping("/getAll")
    @ApiOperation("获取用户地址")
    public BaseResponse<List<DeliveryAddressVo>> getAll(HttpServletRequest httpServletRequest) {
        List<DeliveryAddress> addresses = service.findAll(httpServletRequest);
        List<DeliveryAddressVo> addressVos = addresses.stream().map(
                address -> modelMapper.map(address, DeliveryAddressVo.class)
        ).collect(Collectors.toList());
        return ResultUtils.success(addressVos);
    }

    @PostMapping("/save")
    @ApiOperation("保存地址")
    public BaseResponse<DeliveryAddressVo> save(@ApiParam("请求参数") @RequestBody UpdateAddressDTO dto, HttpServletRequest httpServletRequest) {
        DeliveryAddress saveAddress = service.saveAddress(dto, httpServletRequest);
        return ResultUtils.success(modelMapper.map(saveAddress, DeliveryAddressVo.class));
    }

    @PostMapping("/update")
    @ApiOperation("更新地址")
    public BaseResponse<DeliveryAddressVo> update(@ApiParam("请求参数") @RequestBody UpdateAddressDTO dto, HttpServletRequest httpServletRequest) {
        DeliveryAddress saveAddress = service.saveAddress(dto, httpServletRequest);
        return ResultUtils.success(modelMapper.map(saveAddress, DeliveryAddressVo.class));
    }

    @GetMapping("/getById/{id}")
    @ApiOperation("获取地址")
    public BaseResponse<DeliveryAddressVo> getById(@ApiParam("id") @PathVariable Long id, HttpServletRequest httpServletRequest) {
        DeliveryAddress address = service.findById(id, httpServletRequest);
        return ResultUtils.success(modelMapper.map(address, DeliveryAddressVo.class));
    }

    @GetMapping("/deleteById/{id}")
    @ApiOperation("删除地址")
    public BaseResponse<DeliveryAddressVo> deleteById(@ApiParam("id") @PathVariable Long id, HttpServletRequest httpServletRequest) {
        DeliveryAddress address = service.deleteById(id, httpServletRequest);
        return ResultUtils.success(modelMapper.map(address, DeliveryAddressVo.class));
    }

}
